from flask import current_app
from sqlalchemy.orm import sessionmaker

class DatabaseHandler:
    def __init__(self, model_class):
        self.model_class = model_class
        self.session = sessionmaker(bind=current_app.extensions['sqlalchemy'].engine)()

    def get_all(self):
        with self.session.begin():
            return self.session.query(self.model_class).all()

    def get_by_id(self, id):
        with self.session.begin():
            return self.session.query(self.model_class).get(id)

    def add(self, instance):
        with self.session.begin():
            self.session.add(instance)

    def delete(self, instance):
        with self.session.begin():
            self.session.delete(instance)

    def commit(self):
        self.session.commit()

    def rollback(self):
        self.session.rollback()
